package com.waves.util;

import lombok.experimental.UtilityClass;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * @Package: com.example.test.aop
 * @Author: Mr.Waves
 * @Date: 2020-02-04 18:28
 * @Description: SpringEL表达式解析器
 **/
@UtilityClass
public class SpringELParser {
    private static final ExpressionParser parser = new SpelExpressionParser();

    /**
     * expression: 字符串表达式
     * paramNames: 参数名集合
     * args: 参数值集合
     */
    public String getResult(String expression, String[] paramNames, Object[] args) {
        if (args.length <= 0) {
            return null;
        }
        // String -> SpringEL -> calculation
        Expression exp = parser.parseExpression(expression);
        EvaluationContext context = new StandardEvaluationContext();
        for (int i = 0; i < args.length; i++) {
            context.setVariable(paramNames[i],args[i]);
        }
        return exp.getValue(context,String.class);
    }
}
